package com.alibaba.citrus.ots.forecast.facade.service;

import com.alibaba.lattice2.epoch.sdk.model.Result;
import com.epoch.app.otsforecastsales.api.forecastorderlinequery.service.ForecastOrderLineQueryService;
import com.epoch.app.otsforecastsales.dto.response.QueryForecastLineResponse;
import com.epoch.app.otsforecastsales.enums.ForecastStatusEnum;
import com.epoch.app.otsforecastsales.model.dto.*;
import com.epoch.app.otsforecastsales.otsforecastorderquery.service.OtsForecastOrderQueryService;
import com.epoch.app.otsforecastsales.otsforecastorderreportsqueryservice.service.OtsForecastOrderReportsQueryServiceService;
import com.epoch.app.otsforecastsales.sdo.ForecastOrderSDO;
import com.epoch.app.otsforecastsales.service.OtsForecastSalesService;
import com.google.common.collect.Lists;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.text.SimpleDateFormat;

import java.util.Date;

import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.util.*;

@Component
public class OtsForecastOrderReportsQueryServiceImpl implements OtsForecastOrderReportsQueryServiceService {

    @Autowired
    private OtsForecastOrderQueryService otsForecastOrderQueryService;

    @Autowired
    private ForecastOrderLineQueryService forecastOrderLineQueryService;

    @Autowired
    private OtsForecastSalesService otsForecastSalesService;

    private List<Integer> STATUS = Lists.newArrayList(ForecastStatusEnum.WAITING_FOR_REPLY.getNumValue(),
            ForecastStatusEnum.PARTIAL_REPLY.getNumValue(),ForecastStatusEnum.COMPLETED.getNumValue());

    @Override
    public Result<ForecastOrderReportsResponse> forecastOrderReportsQuery(ForecastOrderReportsRequest forecastOrderReportsRequest) {
        ForecastOrderReportsResponse forecastOrderReportsResponse = new ForecastOrderReportsResponse();
//        //主单数量
//        List<ForecastOrderSDO> orderSDOS = queryOrderList(null,null);
//        //提报单量
//        String ordersSize = getOrdersSize(orderSDOS);
//        forecastOrderReportsResponse.setOrdersSize(ordersSize);
//        //提报单量较前一天比值
//        String ordersCompare = getOrdersCompare();
//        forecastOrderReportsResponse.setOrdersCompare(ordersCompare);
//        //提报单量单位
//        String orderSizeUnit = null;
//        if(CollectionUtils.isEmpty(orderSDOS)){
//            orderSizeUnit = "单";
//        }
//        orderSizeUnit = getUnit(orderSDOS.size());
//        forecastOrderReportsResponse.setOrdersSizeUnit(orderSizeUnit);
//        //提报单量较前日比值符号
//        String orderSizeSign = getSign(ordersCompare);
//        forecastOrderReportsResponse.setOrdersSizeSign(orderSizeSign);
//
//        //已回复单量
//        Integer repliedOrderSize = getRepliedOrderSize();
//        forecastOrderReportsResponse.setRepliedOrderSize(fmtMicrometer(repliedOrderSize + ""));
//
//        //已回复单量较前一日比值
//        String repliedOrderSizeCompare = getRepliedOrderSizeCompare();
//        forecastOrderReportsResponse.setRepliedOrderSizeCompare(repliedOrderSizeCompare + "%");
//
//        //已回复单量单位
//        String repliedOrderSizeUnit = getUnit(repliedOrderSize);
//        forecastOrderReportsResponse.setRepliedOrderSizeUnit(repliedOrderSizeUnit);
//
//        //比值符号
//        String repliedOrderSizeSign = getSign(repliedOrderSizeCompare);
//        forecastOrderReportsResponse.setRepliedOrderSizeSign(repliedOrderSizeSign);
//
//        //已回复单量/提报量 = 占比
//        String[] res = getProportionOfReplies((CollectionUtils.isEmpty(orderSDOS)?0:orderSDOS.size()),repliedOrderSize);
//        if(Objects.nonNull(res) && res.length > 1){
//            forecastOrderReportsResponse.setOrdersProportionOfReplies(res[0]);
//            forecastOrderReportsResponse.setOrderSizeTail(res[1]);
//        }
//
//        //子单总件数
//        CountQuantityForReportResponse orderLines = queryOrderLine(null,null);
//        Integer quantity = orderLines.getQuantity();
//        forecastOrderReportsResponse.setOrderDetailsSize(fmtMicrometer(quantity  + ""));
//
//        //单位
//        String orderDetailsSizeUnit = getUnit(orderLines.getQuantity());
//        forecastOrderReportsResponse.setOrderDetailsSizeUnit(orderDetailsSizeUnit);
//
//        String orderDetailsCompare = getRepliedOrderDetailsCompare(0) + "%";
//        forecastOrderReportsResponse.setOrderDetailsCompare(orderDetailsCompare);
//
//        //
//        String orderDetailsSizeSign = getSign(orderDetailsCompare);
//        forecastOrderReportsResponse.setOrderDetailsSizeSign(orderDetailsSizeSign);
//
//
//        Integer repliedOrderDetailsSize = orderLines.getActualTotalReplyAmount();
//        forecastOrderReportsResponse.setRepliedOrderDetailsSize(fmtMicrometer(repliedOrderDetailsSize + ""));
//
//        String repliedOrderDetailsCompare = getRepliedOrderDetailsCompare(1);
//        forecastOrderReportsResponse.setRepliedOrderDetailsCompare(repliedOrderDetailsCompare);
//
//        String repliedOrderDetailsSizeUnit = getUnit(repliedOrderDetailsSize);
//        forecastOrderReportsResponse.setRepliedOrderDetailsSizeUnit(repliedOrderDetailsSizeUnit);
//
//        String repliedOrderDetailsSizeSign = getSign(repliedOrderDetailsCompare);
//        forecastOrderReportsResponse.setRepliedOrderDetailsSizeSign(repliedOrderDetailsSizeSign);
//
//        String[] res2 = getProportionOfReplies(quantity,repliedOrderDetailsSize);
//        if(Objects.nonNull(res2) && res.length > 1){
//            forecastOrderReportsResponse.setOrderDetailsProportionOfReplies(res2[0]);
//            forecastOrderReportsResponse.setOrderDetailTail(res2[1]);
//        }

        //处理top5



        return Result.success(mockData());
    }



    private String getRepliedOrderDetailsCompare(Integer type){
        CountForecastQuantityForReportResponse today = queryOrderLine(null,getToday());
        CountForecastQuantityForReportResponse yesterday = queryOrderLine(null,getYesterdays());
        if(Objects.isNull(today) || Objects.isNull(yesterday)){
            return null;
        }
        if(new Integer(0).equals(type)){
            Integer todaySum = today.getQuantity();
            Integer yesterdaySum = yesterday.getQuantity();
            BigDecimal result = (new BigDecimal(todaySum).subtract(new BigDecimal(yesterdaySum))).
                    divide(new BigDecimal(yesterdaySum),2,BigDecimal.ROUND_HALF_UP);
            return result + "";
        }
        Integer todaySum = today.getActualTotalReplyAmount();
        Integer yesterdaySum = yesterday.getActualTotalReplyAmount();
        BigDecimal result = (new BigDecimal(todaySum).subtract(new BigDecimal(yesterdaySum))).
                divide(new BigDecimal(yesterdaySum),2,BigDecimal.ROUND_HALF_UP);
        return result + "";


    }

//    private Integer orderLineSubNum(List<QueryForecastLineResponse> orderLines){
//        if(CollectionUtils.isEmpty(orderLines)){
//            return null;
//        }
//        return orderLines.stream().map(QueryForecastLineResponse::getQuantity).reduce(0,Integer::sum);
//    }

    private String[] getProportionOfReplies(Integer orders, Integer repliesOrders){
        BigDecimal result = new BigDecimal((Objects.isNull(repliesOrders)?0:repliesOrders)).
                divide(new BigDecimal((Objects.isNull(orders)?0:orders)));
        return result.toString().split("\\.");
    }

    private String getRepliedOrderSizeCompare(){
        Integer yesterdaysSize = 0;
        Integer todaySize = 0;
        List<ForecastOrderSDO> yesterdaysList = queryOrderList(getYesterdays(), STATUS);
        List<ForecastOrderSDO> todayList = queryOrderList(getToday(), STATUS);

        yesterdaysSize = (CollectionUtils.isEmpty(yesterdaysList)?0:yesterdaysList.size());

        todaySize = (CollectionUtils.isEmpty(todayList)?0:todayList.size());

        BigDecimal result = (new BigDecimal(todaySize).subtract(new BigDecimal(yesterdaysSize))).
                divide(new BigDecimal(yesterdaysSize),2,BigDecimal.ROUND_HALF_UP);
        return result + "";
    }

    private Integer getRepliedOrderSize(){
        //状态为2、3和4之和
        List<ForecastOrderSDO> forecastOrderSDOS = queryOrderList(null, STATUS);
        if(CollectionUtils.isEmpty(forecastOrderSDOS)){
            return null;
        }
        return forecastOrderSDOS.size();
    }

    private String getSign(String ordersCompare){
        if(StringUtils.isBlank(ordersCompare)){
            return null;
        }
        if(ordersCompare.contains("-")){
            return "-1";
        }
        if(ordersCompare.contains("0.00")){
            return "0";
        }
        return "1";
    }

    private String getUnit(Integer size){
        if(Objects.isNull(size)){
            return null;
        }
        if(size > 100000){
            return "万单";
        }
        return "单";
    }


    private String getOrdersSize(List<ForecastOrderSDO> orderSDOS){
        if(CollectionUtils.isEmpty(orderSDOS)){
            return null;
        }
        Integer size = orderSDOS.size();
        if(size > 100000){
            size = size / 100000;
        }
        String formatInteger = fmtMicrometer(size + "");
        return formatInteger;
    }

    private String getOrdersCompare(){
        Integer yesterdaysSize = 0;
        Integer todaySize = 0;
        List<ForecastOrderSDO> yesterdaysList = queryOrderList(getYesterdays(),null);
        List<ForecastOrderSDO> todayList = queryOrderList(getToday(),null);
        if(CollectionUtils.isNotEmpty(yesterdaysList)){
            yesterdaysSize = yesterdaysList.size();
        }
        if(CollectionUtils.isNotEmpty(todayList)){
            todaySize = todayList.size();
        }

        BigDecimal result = (new BigDecimal(todaySize).subtract(new BigDecimal(yesterdaysSize))).
                divide(new BigDecimal(yesterdaysSize),2,BigDecimal.ROUND_HALF_UP);
        return result + "";
    }





    private List<ForecastOrderSDO> queryOrderList(List<String> dates, List<Integer> status){
        PageQueryForecastRequest request = new PageQueryForecastRequest();
        if(CollectionUtils.isNotEmpty(dates)){
            request.setGmtCreate(dates);
        }
        if(Objects.nonNull(status)){
            request.setMainStatusList(status);
        }

        Result<List<ForecastOrderSDO>> listResult = otsForecastOrderQueryService.queryForecastOrderList(request);
        if(Objects.isNull(listResult)){
            return null;
        }
        List<ForecastOrderSDO> forecastOrderSDOS = listResult.getResult();
        if(CollectionUtils.isEmpty(forecastOrderSDOS)){
            return null;
        }
        return forecastOrderSDOS;
    }

    private CountForecastQuantityForReportResponse queryOrderLine(List<Integer> status, List<String> gmtCreate){
        CountForecastQuantityForReportRequest request = new CountForecastQuantityForReportRequest();
        if(CollectionUtils.isNotEmpty(status)){
//            request.setDetailStatus(status);
        }

        CountForecastQuantityForReportResponse result = otsForecastSalesService.countForecastQuantityForReport(request);
        if(Objects.isNull(result)){
            return null;
        }

        return result;
    }



    private ForecastOrderReportsResponse mockData(){
        ForecastOrderReportsResponse res = new ForecastOrderReportsResponse();
        List<ForecastOrderReportsTopListResponse> list = Lists.newArrayList();
        for(int i = 0;i < 2; i++){
            ForecastOrderReportsTopListResponse top = new ForecastOrderReportsTopListResponse();
            top.setName("订单回复");
            top.setNum("1234件");
            top.setPercent(new BigDecimal(72.23));
            list.add(top);
        }
        for(int i = 0;i < 3; i++){
            ForecastOrderReportsTopListResponse top = new ForecastOrderReportsTopListResponse();
            top.setName("价格差异");
            top.setNum("15233件");
            top.setPercent(new BigDecimal(46.56));
            list.add(top);
        }
        res.setForecastOrderReportsTopList(list);
        res.setOrdersSize("20,000");
        res.setOrdersSizeUnit("单");
        res.setOrderDetailsCompare("+1.50%");
        res.setRepliedOrderSize("18,000");
        res.setRepliedOrderSizeCompare("-1.50%");
        res.setRepliedOrderSizeUnit("单");
        res.setOrdersProportionOfReplies("90");
        res.setOrdersSizeSign("1");
        res.setRepliedOrderSizeSign("-1");
        res.setOrderSizeTail(".00%");

        res.setOrderDetailsSize("30,000");
        res.setOrderDetailsSizeUnit("件");
        res.setOrderDetailsCompare("+1.50%");
        res.setRepliedOrderDetailsSize("21,000");
        res.setRepliedOrderDetailsSizeUnit("件");
        res.setOrderDetailsCompare("-1.50%");
        res.setOrderDetailsProportionOfReplies("70");
        res.setOrderDetailsSizeSign("1");
        res.setRepliedOrderDetailsSizeSign("-1");
        res.setOrderDetailTail(".01%");
        return res;
    }

    public static void main(String[] args) {

        BigDecimal result = (new BigDecimal(90).subtract(new BigDecimal(100))).
                divide(new BigDecimal(100),2,BigDecimal.ROUND_HALF_UP);

        String[] array = (result+"").split("\\.");
        System.out.println(array);

    }

    private static List<String> getYesterdays(){
        SimpleDateFormat sdf=new SimpleDateFormat("yyy-MM-dd");
        Calendar calendar = new GregorianCalendar();
        calendar.setTime(new Date());
        calendar.add(calendar.DATE,-1);
        String date= sdf.format(calendar.getTime());
        String start = " 00:00:00";
        String end = " 23:59:59";
        List<String> dates = Lists.newArrayList();
        dates.add(0, date + start);
        dates.add(1,date+ end);
        return dates;
    }

    private static List<String> getToday(){
        SimpleDateFormat sdf=new SimpleDateFormat("yyy-MM-dd");
        String date = sdf.format(new Date());
        String start = " 00:00:00";
        String end = " 23:59:59";
        List<String> dates = Lists.newArrayList();
        dates.add(0, date + start);
        dates.add(1,date+ end);
        return dates;
    }

    public static String fmtMicrometer(String text)
    {
        DecimalFormat df = null;
        if(text.indexOf(".") > 0)
        {
            if(text.length() - text.indexOf(".")-1 == 0)
            {
                df = new DecimalFormat("###,##0.");
            }else if(text.length() - text.indexOf(".")-1 == 1)
            {
                df = new DecimalFormat("###,##0.0");
            }else
            {
                df = new DecimalFormat("###,##0.00");
            }
        }else
        {
            df = new DecimalFormat("###,##0");
        }
        double number = 0.0;
        try {
            number = Double.parseDouble(text);
        } catch (Exception e) {
            number = 0.0;
        }
        return df.format(number);
    }



}
